// 人员 设备详情组件，包括 模板，emitter事件等
import Component from "../Component.js";
import ServiceUtils from "../../experience/other/shanxi/ServiceUtils.js";
import Type from "../../experience/db/Type.js";
import { _toast } from "../../experience/utils/F7.js"

const MultiLineString = ol.geom.MultiLineString;
const Feature = ol.Feature;
const Point = ol.geom.Point;
const Fill = ol.style.Fill;
const Style = ol.style.Style;
const Icon = ol.style.Icon;
const LineString = ol.geom.LineString;

export default class MstaffDetail extends Component {
    constructor() {
        super();
    }

    template() {
        const mstaffDetailPopup = `
            <div id="mstaffDetail" class="deviceDetail" style="width: 500px;height: 250px;">
                <div class="detailheader">
                    <span class="title">人员信息</span>
                    <i id="mstaffDetailClosePan" class="fas fa-times closeIcon"></i>
                </div>
                <div class="detailcontent">
                
                </div>  
                <button style="border-color: #0c82df;border-radius: 5px;width: 100px;height: 35px;font-size: 12px;background-color: #0c82df;color: white;margin: 10px" id="staffTrackReplay">人员轨迹回放</button> 
            </div>
        `
        this.$$("#article").append(mstaffDetailPopup);
    }

    async control() {
        this.ServiceUtils = new ServiceUtils()
        // 创建 overlay
        this.deviceDetailOverlay = this.drawer.addOverlay('mstaffDetail','mstaffDetailClosePan')
        this.deviceDetailOverlay.setOffset([10,10])
        this.staffTrackData = null
        // 绑定轨迹回放按钮 回调函数
        this.$$('#staffTrackReplay').on('click', () => {
            if(this.staffTrackData == null || this.staffTrackData.length == 0) {
                _toast('当前人员暂无轨迹信息')
            }
            else {
                this.trackReplay()
            }
        })
        // 相关 emit事件的初始化
        this.emitEventInit()

    }

    emitEventInit() {
        const mode = this.utils.getUrlParamer('edit')
        const meta_id = this.utils.getUrlParamer('meta_id')
        const flag = mode == 'true' ? true : false
        this.emitter.on('mstaff-detail-open',async () => {
            if(flag) {
                return
            }

            const detailContent = this.$$('#mstaffDetail .detailcontent')
            detailContent.empty()
            const targetArgument = this.emitter.params[0]
            const device_id = targetArgument.get('device_id')
            const coordinate = targetArgument.getGeometry().getCoordinates()
            this.deviceDetailOverlay.setPosition(coordinate)

            const {data: staffs} = await this.api.current_staff_data(meta_id)

            const enableNode = staffs.find((staff) => {
                return staff.StaffId == device_id
            })

            const stationFeatures = this.drawer.source(Type.M_Station).getFeatures()
            for(let i = 0;i < stationFeatures.length;i++) {
                if(stationFeatures[i].get('device_id') == enableNode.CurStationId) {
                    const belongStationName = stationFeatures[i].getStyle().getText().getText()
                    enableNode.currentStationName = belongStationName
                    break
                }
            }
            const EnterStationDateArr = enableNode.EnterStationTime.split('T')
            const detailInfoContent = `
                <div class="infoitem">
                     <div class="detailname">员工编号</div>
                     <div class="detailval">${enableNode.StaffId}</div>              
                </div>
                <div class="infoitem">
                     <div class="detailname">员工名称</div>
                     <div class="detailval">${enableNode.Name}</div>              
                </div>
                <div class="infoitem">
                     <div class="detailname">所属部门</div>
                     <div class="detailval">${enableNode.DepartMent}</div>              
                </div>
                <div class="infoitem">
                     <div class="detailname">职务名称</div>
                     <div class="detailval">${enableNode.JobName}</div>              
                </div>
                <div class="infoitem">
                     <div class="detailname">当前分站名称</div>
                     <div class="detailval">${enableNode.currentStationName}</div>              
                </div>
                <div class="infoitem">
                     <div class="detailname">进入分站时间</div>
                     <div class="detailval">${EnterStationDateArr[0] + ' ' + EnterStationDateArr[1]}</div>              
                </div>
                <div class="infoitem">
                     <div class="detailname">责任</div>
                     <div class="detailval">${enableNode.Duty}</div>              
                </div>
            `
            detailContent.append(detailInfoContent)
            // 每次打开人员信息弹窗 就重新获取一次轨迹信息
            const {data} = await this.api.shanxiStaffTrack(meta_id,enableNode.StaffId)
            this.staffTrackData = data
        })
    }

    trackReplay() {
        console.log('当前人员的轨迹信息为  ', this.staffTrackData)
        _toast("按下Esc键退出轨迹回放");
        this.deviceDetailOverlay.setPosition(undefined)
        this.drawer.drawer.m_staff.setVisible(false)
        this.drawer.drawer.k_station.setVisible(false)
        this.drawer.drawer.k_node.setVisible(false)
        this.drawer.drawer.v_camera.setVisible(false)
        // 按下 Esc退出 人员轨迹回放
        window.onkeydown = (event) => {
            if (event.defaultPrevented) return;
            let handled = false;
            if (event.key === "Escape") {

                this.drawer.drawer.m_staff.setVisible(true)
                this.drawer.drawer.k_station.setVisible(true)
                this.drawer.drawer.k_node.setVisible(true)
                this.drawer.drawer.v_camera.setVisible(true)
                window.onkeydown = null;
                _toast("人员轨迹回放停止");
                this.emitter.emit('refresh-valve',true) // 重新打开阀门
                try {
                    clearInterval(this.trackReplayTimer)
                }
                catch (e) {

                }
                this.drawer.source(Type.Modify).clear()
            }
            if (handled) event.preventDefault();
        }

        this.drawStaffTrackPath()
    }

    drawStaffTrackPath() {
        let trackIsValid = true
        const stationFeatures = this.drawer.source(Type.M_Station).getFeatures()
        for(let i = 0;i < this.staffTrackData.length;i++) {
            if(stationFeatures.find((s) => { return s.get('device_id') == this.staffTrackData[i] }) ) {
                trackIsValid = trackIsValid && true
            }
            else {
                trackIsValid = trackIsValid && false
                break
            }
        }
        if(trackIsValid) {
            // 正式 开始轨迹
            this.emitter.emit('refresh-valve',false)  // 将控制设备更新的阀门 关闭
            const trackCoordinateArr = []
            this.staffTrackData.forEach((trackitem) => {
                const enableFeature = stationFeatures.find((f) => {
                    return f.get('device_id') == trackitem
                })
                trackCoordinateArr.push(enableFeature.getGeometry().getCoordinates())
            })
            const movingCoordinateArr = []
            // 创建 折线
            const lineStringArr = []
            // 记录 轨迹上的最大，最小，x，y坐标
            let min_x = trackCoordinateArr[0][0],min_y = trackCoordinateArr[0][1],max_x = trackCoordinateArr[0][0],max_y = trackCoordinateArr[0][1]
            for(let index = 0;index < trackCoordinateArr.length;index++) {
                // 记录轨迹区域内的最大，最小坐标
                if(trackCoordinateArr[index][0] < min_x) {
                    min_x = trackCoordinateArr[index][0]
                }
                if(trackCoordinateArr[index][0] >= max_x) {
                    max_x = trackCoordinateArr[index][0]
                }
                if(trackCoordinateArr[index][1] < min_y) {
                    min_y = trackCoordinateArr[index][1]
                }
                if(trackCoordinateArr[index][1] >= max_y) {
                    max_y = trackCoordinateArr[index][1]
                }


                if(index == (trackCoordinateArr.length - 1)) {
                    break
                }
                const line = new LineString([trackCoordinateArr[index],trackCoordinateArr[index+1]])
                lineStringArr.push(line)
                const step_x = (trackCoordinateArr[index+1][0] -  trackCoordinateArr[index][0]) / 50,step_y = (trackCoordinateArr[index+1][1] -  trackCoordinateArr[index][1]) / 50
                for(let i = 1;i <= 50;i++) {
                    movingCoordinateArr.push([trackCoordinateArr[index][0] + i * step_x,trackCoordinateArr[index][1] + i * step_y])
                }
            }

            // 将gis上能看到的区域限制在这个 轨迹线的区域中。
            const view = this.drawer.map.getView()
            const resolution = view.getResolutionForExtent([min_x,min_y,max_x,max_y]) + 100
            view.setResolution(resolution)
            const multiLine = new MultiLineString(lineStringArr)
            const trackPath = new Feature(multiLine)
            this.drawer.source(Type.Modify).addFeature(trackPath)
            this.drawer.map.getView().setCenter([(min_x + max_x) / 2,(min_y + max_y) / 2])
            // 添加小人 让他 在轨迹上进行移动
            const staffMovingIcon = new Icon({
                src: 'assets/images/shanxi/staff_moving.png',
                scale: '0.6'
            })
            const staffMovingStyle = new Style({
                image: staffMovingIcon
            })
            const staffMovingFeature = new Feature(new Point(trackCoordinateArr[0]))
            staffMovingFeature.setStyle(staffMovingStyle)
            this.drawer.source(Type.Modify).addFeature(staffMovingFeature)

            // 人员轨迹回放 走动的坐标列表计数器
            let timerCount = 0
            this.trackReplayTimer = setInterval(() => {
                if(timerCount < movingCoordinateArr.length) {
                    staffMovingFeature.getGeometry().setCoordinates(movingCoordinateArr[timerCount])
                    timerCount++
                }
                else {
                    clearInterval(this.trackReplayTimer)
                    this.emitter.emit('refresh-valve',true) // 重新打开阀门
                    window.onkeydown = null
                    this.drawer.drawer.m_staff.setVisible(true)
                    this.drawer.drawer.k_station.setVisible(true)
                    this.drawer.drawer.k_node.setVisible(true)
                    this.drawer.drawer.v_camera.setVisible(true)
                    this.drawer.source(Type.Modify).clear()
                }
            },350)

        }
        else {
            this.app.dialog.alert('存在轨迹上的分站未被设置位置','提示')
            window.onkeydown = null
            this.drawer.drawer.m_staff.setVisible(true)
            this.drawer.drawer.k_station.setVisible(true)
            this.drawer.drawer.k_node.setVisible(true)
            this.drawer.drawer.v_camera.setVisible(true)

        }
    }
}
